const express = require("express")
const { v4 } = require("uuid")
const moment = require("moment")
const { query } = require("../db/db")

const router = express.Router()

router.get("/list", (req, res) => {
  const sql = `select * from blog_todo where delete_state = '1' order by update_time desc, create_time desc`
  query(sql)
    .then((data) => {
      const completeds = data.data.filter((o) => {
        return o.state === "2"
      })

      const uncompleteds = data.data.filter((o) => {
        return o.state === "1"
      })

      res.json({
        code: 200,
        msg: "ok",
        data: {
          completeds,
          uncompleteds
        }
      })
    })
    .catch((err) => {
      console.log(err)
      res.json({
        code: 4001,
        msg: "获取待办列表失败",
        data: null
      })
    })
})

router.post("/create", (req, res) => {
  const { todo, state } = req.body
  const sql = `insert into blog_todo set ?`
  const value = {
    id: v4().toString().replace(/-/g, ""),
    todo,
    state,
    create_time: moment().format("yyyy-MM-DD HH:mm:ss")
  }

  query(sql, value)
    .then(() => {
      res.json({
        code: 200,
        msg: "新增成功！",
        data: []
      })
    })
    .catch((err) => {
      res.json({
        code: 4001,
        msg: "新增失败",
        data: null
      })
    })
})

router.post("/delete", (req, res) => {
  const { id } = req.body
  const sql = `update blog_todo set delete_state=? where id=?`
  const value = ["2", id]
  query(sql, value)
    .then(() => {
      res.json({
        code: 200,
        msg: "删除成功！",
        data: []
      })
    })
    .catch((err) => {
      console.log(err)
      res.json({
        code: 4001,
        msg: "删除失败！",
        data: null
      })
    })
})

router.post("/updateState", (req, res) => {
  const { id, state, todo } = req.body
  let sql = `update blog_todo set state=? where id=?`
  let value = [state === "1" ? "2" : "1", id]
  if (todo) {
    sql = `update blog_todo set state=?,todo=? ,update_time=? where id=?`
    value = [state, todo, moment().format("yyyy-MM-DD HH:mm:ss"), id]
  }
  query(sql, value)
    .then(() => {
      res.json({
        code: 200,
        msg: "更新成功！",
        data: []
      })
    })
    .catch((err) => {
      console.log(err)
      res.json({
        code: 4001,
        msg: "更新失败！",
        data: null
      })
    })
})

module.exports = router
